import axios from 'axios'

const FileURL = 'http://file.linhsy.com'
let BaseURL = ''
const protocol = window.location.protocol
const serverUrl = window.location.host
if (process.env.NODE_ENV === 'development') {
    BaseURL = process.env.VUE_APP_DEV_SERVER
} else {
    BaseURL = protocol + '//' + serverUrl
    FileURL = protocol + '//file.linhsy.com'
}
axios.defaults.baseURL = BaseURL

axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('dangjianToken')
    const noAuthUrls = ['login']
    if (!noAuthUrls.find(url => config.url.indexOf(url) > -1)) {
        if (token) {
            config.headers.accessToken = `${token}`
        } else {
            window.location.pathname = '/login'
        }
    }
    return config
  },
  error => {
    return error
  }
)

axios.interceptors.response.use(
    response => {
        const errorCode = response.data.code
        const errorMsg = response.data.msg
        if (errorCode !== 200) {
            handleError(errorCode, errorMsg)
            console.log(`errorCode = ${errorCode}, errorMsg = ${errorMsg}`)
        }
        return response
    },
    error => {
        const errorCode = error.response.data && error.response.data.code || error.response.status || ''
        const errorMsg = error.response.data && error.response.data.msg || error.response.statusText || error || ''
        handleError(errorCode, errorMsg || errorCode)
        console.log(`errorCode = ${errorCode}, errorMsg = ${errorMsg}`)
        return Promise.reject(error)
    }
)

function handleError(errorCode = 200, errorMsg = '') {
    if ((errorCode === 401 || errorCode === 403) && window.location.pathname.indexOf('login') < 0) {
        window.location.href = '/login'
    } else if (errorCode !== 200) {
        window.vm.$Message.error({
            background: true,
            content: errorMsg
        })
    }
}

export { axios, BaseURL, FileURL }
